package com.cpp.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cpp.common.exception.BaseException;
import com.cpp.common.properties.PageProperties;
import com.cpp.common.result.PageResult;
import com.cpp.pojo.dto.user.UserCreateDTO;
import com.cpp.pojo.dto.user.UserLoginDTO;
import com.cpp.pojo.dto.user.UserPageDTO;
import com.cpp.pojo.dto.user.UserUpdateDTO;
import com.cpp.common.enums.UserRoleEnum;
import com.cpp.pojo.pojo.User;
import com.cpp.pojo.vo.user.UserVO;
import com.cpp.server.aspect.annotation.UserRole;
import com.cpp.server.context.UserHolder;
import com.cpp.server.mapper.UserMapper;
import com.cpp.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PageProperties pageProperties;

    public static final String defaultPassword = "123";
    @Override
    @UserRole(roles = UserRoleEnum.ADMIN)
    public void saveUser(UserCreateDTO userCreateDTO) {
        //业务逻辑判断数据准备
        User currentUser = UserHolder.getCurrentUser();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, userCreateDTO.getUsername());
        User one = getOne(queryWrapper);

        if (one!=null){
            throw new BaseException("该用户名已存在，换一个试试吧");
        }

        User user = User.builder()
                .username(userCreateDTO.getUsername())
                .realName(userCreateDTO.getRealName())
                .password(defaultPassword)
                .sex(userCreateDTO.getSex())
//                .imageUrl(userCreateDTO.getImageUrl())
                .role(userCreateDTO.getRole())
                .creatorId(currentUser.getId())
                .build();

        userMapper.insert(user);
    }

    @Override
    public User login(UserLoginDTO userLoginDTO) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, userLoginDTO.getUsername());
        User user = getOne(queryWrapper);

        if (user==null){
           throw new BaseException("该用户不存在");
        }
        if (!user.getPassword().equals(userLoginDTO.getPassword())){
            throw new BaseException("密码错误");
        }

        return user;
    }

    @Override
    @UserRole(roles = UserRoleEnum.ADMIN)
    public PageResult list(UserPageDTO userPageDTO) {

        if (userPageDTO.getPage()==null){
            userPageDTO.setPage(pageProperties.getPage());
        }
        if (userPageDTO.getPageSize()==null){
            userPageDTO.setPageSize(pageProperties.getPageSize());
        }

        String username = userPageDTO.getUsername();
        String role = userPageDTO.getRole();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(username!= null && !username.isEmpty(),User::getUsername, userPageDTO.getUsername());
        queryWrapper.eq( role!= null && !role.isEmpty(),User::getRole, userPageDTO.getRole());

        // 使用 MyBatis Plus 分页：当前页码、每页条数
        Page<User> page = new Page<>(userPageDTO.getPage(), userPageDTO.getPageSize());

        // 执行分页查询
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        List<User> records = userPage.getRecords();
        List<UserVO> userVOS = new ArrayList<>();
        for (User record : records) {
            UserVO userVO = UserVO.builder()
                    .userId(record.getId())
                    .username(record.getUsername())
                    .realName(record.getRealName())
                    .sex(record.getSex().equals("1")?"男":"女")
                    .imageUrl(record.getImageUrl())
                    .role(record.getRole())
                    .build();
            userVOS.add(userVO);
        }


        // 封装为自定义的 PageResult 返回
        return new PageResult(userPage.getTotal(), userVOS);
    }

    @Override
    @UserRole(roles = UserRoleEnum.ADMIN)
    public void removeByIds(List<Long> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    @UserRole(roles = UserRoleEnum.ADMIN)
    public void updateUser(UserUpdateDTO userUpdateDTO) {
        //获取逻辑数据
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, userUpdateDTO.getUsername());
        User one = getOne(wrapper);
        if (one==null&&one.getId()!=userUpdateDTO.getUserId()){
//            System.out.println(one.toString()+userUpdateDTO.toString());
            throw new BaseException("该用户名已存在换一个试试把");
        }

        //获取业务数据
        String username = userUpdateDTO.getUsername();
        String role = userUpdateDTO.getRole();
        String realName = userUpdateDTO.getRealName();
        String sex = userUpdateDTO.getSex();
        String imageUrl = userUpdateDTO.getImageUrl();

        //封装数据
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(!username.isEmpty(),User::getUsername, username);
        updateWrapper.set(!role.isEmpty(),User::getRole, role);
        updateWrapper.set(!realName.isEmpty(),User::getRealName, realName);
        updateWrapper.set(!sex.isEmpty(),User::getSex, sex);
        updateWrapper.set(!imageUrl.isEmpty(),User::getImageUrl, imageUrl);
        updateWrapper.eq(User::getId, userUpdateDTO.getUserId());

        userMapper.update(updateWrapper);
    }


}
